<?php
session_start();
require 'check_login.php';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>文件管理系统</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* 自定义样式 */
        body {
            background-color: #f8f9fa;
        }
        h1 {
            margin-bottom: 30px;
        }
        .table thead th {
            background-color: #343a40;
            color: #fff;
        }
        .btn {
            margin-right: 5px;
        }
        .alert {
            margin-top: 20px;
        }
        /* 上传按钮宽度为100% */
        #upload-form .btn {
            width: 100%;
        }
        /* 拖拽区域样式 */
        #drop-area {
            border: 2px dashed #6c757d;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            color: #6c757d;
            margin-bottom: 20px;
            transition: background-color 0.3s, border-color 0.3s;
            position: relative;
            cursor: pointer;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        #drop-area.highlight {
            border-color: #495057;
            background-color: #e9ecef;
            color: #495057;
        }
        /* 隐藏实际的文件输入 */
        #file-input {
            display: none;
        }
        /* 文件预览样式 */
        #file-preview {
            margin-top: 20px;
            display: none;
            border: 1px solid #ced4da;
            padding: 15px;
            border-radius: 5px;
            background-color: #ffffff;
        }
        #file-preview img {
            max-width: 100%;
            height: auto;
            margin-bottom: 10px;
        }

        /* 为表格添加圆角 */
        .table-responsive .table {
            border-radius: 10px;
            overflow: hidden;
        }

        /* 访问权限切换按钮样式 */
        .toggle-access {
            color: #0d6efd;
            cursor: pointer;
        }

        .toggle-access:hover {
            color: #0b5ed7;
        }

        /* 响应式隐藏列 */
        @media (max-width: 767.98px) {
            .file-size, .upload-time, .uploader-name {
                display: none;
            }
            table thead tr th:nth-child(2),
            table thead tr th:nth-child(3),
            table thead tr th:nth-child(4),
            table thead tr th:nth-child(5), /* 隐藏第5列：访问权限 */
            table tbody tr td.file-size,
            table tbody tr td.upload-time,
            table tbody tr td.uploader-name,
            table tbody tr td:nth-child(5) { /* 隐藏第5列：访问权限 */
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <h1 class="text-center">内网文件管理系统</h1>

        <!-- 显示欢迎信息和退出按钮 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <span>欢迎，<?php echo htmlspecialchars($_SESSION['user']['name']); ?></span>
            </div>
            <div>
                <a href="register.php" class="btn btn-sm btn-outline-secondary">账号注册</a>
                <a href="logout.php" class="btn btn-sm btn-outline-secondary">退出登录</a>
            </div>
        </div>

        <!-- 拖拽上传区域 -->
        <div id="drop-area">
            <span>拖拽文件到此处上传，或点击选择文件。</span>
            <input type="file" name="file" id="file-input" accept="*/*">
            
            <!-- 访问权限选择 -->
            <div class="mt-3">
                <label class="form-label me-3">文件访问权限：</label>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="access" id="public" value="public" checked>
                    <label class="form-check-label" for="public">公开</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="access" id="private" value="private">
                    <label class="form-check-label" for="private">私密</label>
                </div>
            </div>
        </div>

        <!-- 文件预览 -->
        <div id="file-preview">
            <h5>文件预览</h5>
            <p><strong>文件名：</strong><span id="preview-name"></span></p>
            <p><strong>文件类型：</strong><span id="preview-type"></span></p>
            <p><strong>文件大小：</strong><span id="preview-size"></span></p>
            <img id="preview-image" src="#" alt="预览图片" style="display: none;">
        </div>

        <!-- 文件上传表单 -->
        <div class="mb-4">
            <form id="upload-form" enctype="multipart/form-data">
                <button type="submit" class="btn btn-primary">上传文件</button>
            </form>
        </div>

        <!-- 提示信息 -->
        <div id="message-container"></div>

        <!-- 文件列表 -->
        <div class="table-responsive custom-rounded-table">
            <table class="table table-striped table-hover mb-0">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th class="file-size">大小</th>
                        <th class="upload-time">上传时间</th>
                        <th class="uploader-name">上传者</th>
                        <th>访问权限</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="file-list">
                    <!-- 文件列表 -->
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 引入脚本 -->
    <script src="js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const uploadForm = document.getElementById('upload-form');
            const fileListTable = document.getElementById('file-list');
            const dropArea = document.getElementById('drop-area');
            const fileInput = document.getElementById('file-input');
            const filePreview = document.getElementById('file-preview');
            const previewName = document.getElementById('preview-name');
            const previewType = document.getElementById('preview-type');
            const previewSize = document.getElementById('preview-size');
            const previewImage = document.getElementById('preview-image');
            let selectedFile = null;
    
            // 加载文件列表
            loadFileList();
    
            // 点击拖拽区域触发文件选择
            dropArea.addEventListener('click', () => {
                fileInput.click();
            });
    
            // 文件选择
            fileInput.addEventListener('change', () => {
                if (fileInput.files.length > 0) {
                    handleFile(fileInput.files[0]);
                }
            });
    
            // 文件上传表单提交
            uploadForm.addEventListener('submit', function (event) {
                event.preventDefault();
    
                if (!selectedFile) {
                    displayMessage('请先选择一个文件。', 'danger');
                    return;
                }
    
                const formData = new FormData();
                formData.append('file', selectedFile);
                
                // 获取选定的访问权限
                const access = document.querySelector('input[name="access"]:checked').value;
                formData.append('access', access);
                
                fetch('file_manager.php', {
                    method: 'POST',
                    body: formData,
                    credentials: 'include' // 确保请求包含会话信息
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 显示提示信息
                            displayMessage('文件上传成功！', 'success');
                            // 重新加载文件列表
                            loadFileList();
                            // 重置表单和预览
                            uploadForm.reset();
                            resetPreview();
                        } else {
                            displayMessage('文件上传失败：' + data.error, 'danger');
                        }
                    })
                    .catch(error => {
                        console.error('文件上传失败:', error);
                        displayMessage('文件上传失败，请稍后重试。', 'danger');
                    });
            });
    
            // 加载文件列表
            function loadFileList() {
                fetch('file_list.php', {
                        method: 'GET',
                        credentials: 'include' // 确保请求包含会话信息
                    })
                    .then(response => response.json())
                    .then(data => {
                        fileListTable.innerHTML = '';
                        data.forEach(file => {
                            const accessBadge = file.access === 'public' ?
                                `<span class="badge bg-success">公开</span>` :
                                `<span class="badge bg-secondary">私密</span>`;
                            
                            const accessToggle = `
                                <button type="button" class="btn btn-sm btn-link toggle-access" data-file-id="${file.id}" data-current-access="${file.access}">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                            `;
                            
                            const row = `
                                <tr>
                                    <td>${escapeHtml(file.original_name)}</td>
                                    <td class="file-size">${formatFileSize(file.size)}</td>
                                    <td class="upload-time">${escapeHtml(file.upload_time)}</td>
                                    <td class="uploader-name">${escapeHtml(file.uploader_name)}</td>
                                    <td>
                                        ${accessBadge}
                                        ${accessToggle}
                                    </td>
                                    <td>
                                        <a href="${escapeHtml(file.path)}" class="btn btn-success btn-sm" download>下载</a>
                                        <button class="btn btn-danger btn-sm" onclick="deleteFile(${file.id})">删除</button>
                                    </td>
                                </tr>
                            `;
                            fileListTable.innerHTML += row;
                        });
    
                        // 初始化切换访问权限按钮的事件
                        document.querySelectorAll('.toggle-access').forEach(button => {
                            button.addEventListener('click', function(event) {
                                const fileId = this.getAttribute('data-file-id');
                                const currentAccess = this.getAttribute('data-current-access');
                                const newAccess = currentAccess === 'public' ? 'private' : 'public';
                                
                                if (confirm(`确定要将文件权限从 "${currentAccess === 'public' ? '公开' : '私密'}" 更改为 "${newAccess === 'public' ? '公开' : '私密'}" 吗？`)) {
                                    // 发送请求更改访问权限
                                    fetch('change_access.php', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/json'
                                        },
                                        credentials: 'include',
                                        body: JSON.stringify({ file_id: fileId, access: newAccess })
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.success) {
                                            displayMessage('文件访问权限已更新。', 'success');
                                            loadFileList();
                                        } else {
                                            displayMessage('更新失败：' + data.error, 'danger');
                                        }
                                    })
                                    .catch(error => {
                                        console.error('更新访问权限失败:', error);
                                        displayMessage('更新失败，请稍后重试。', 'danger');
                                    });
                                }
                            });
                        });
                    })
                    .catch(error => {
                        console.error('加载文件列表失败:', error);
                        displayMessage('加载文件列表失败，请刷新页面重试。', 'danger');
                    });
            }
    
            // 删除文件
            window.deleteFile = function (fileId) {
                if (confirm('确定要删除这个文件吗？')) {
                    fetch(`delete_file.php?id=${fileId}`, {
                        method: 'GET',
                        credentials: 'include' // 确保请求包含会话信息
                    })
                        .then(response => response.text())
                        .then(data => {
                            // 显示提示信息
                            displayMessage(data, 'success');
                            // 重新加载文件列表
                            loadFileList();
                        })
                        .catch(error => {
                            console.error('删除失败:', error);
                            displayMessage('删除失败，请稍后重试。', 'danger');
                        });
                }
            };
    
            // 防止文件被误拖拽到浏览器窗口
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                document.addEventListener(eventName, preventDefaults, false);
            });
    
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
    
            // 高亮拖拽区域
            ['dragenter', 'dragover'].forEach(eventName => {
                dropArea.addEventListener(eventName, () => dropArea.classList.add('highlight'), false);
            });
    
            ['dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, () => dropArea.classList.remove('highlight'), false);
            });
    
            // 处理拖拽文件
            dropArea.addEventListener('drop', handleDrop, false);
    
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
    
                if (files.length > 0) {
                    if (files.length > 1) {
                        displayMessage('一次只能上传一个文件。', 'warning');
                        return;
                    }
    
                    handleFile(files[0]);
                }
            }
    
            // 处理选中文件并显示预览
            function handleFile(file) {
                console.log('处理文件:', file.name);
                // 阻止上传 .php 文件
                const fileName = file.name.toLowerCase();
                if (fileName.endsWith('.php')) {
                    displayMessage('不允许上传 PHP 文件。', 'warning');
                    resetPreview();
                    return;
                }
    
                const maxSize = 300 * 1024 * 1024; // 300MB
                if (file.size > maxSize) {
                    displayMessage('文件大小超过限制 (最大300MB)。', 'warning');
                    resetPreview();
                    return;
                }
    
                selectedFile = file;
                previewName.textContent = file.name;
                previewType.textContent = file.type || 'N/A';
                previewSize.textContent = formatFileSize(file.size);
    
                // 如果是图片类型，显示预览
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        previewImage.src = e.target.result;
                        previewImage.style.display = 'block';
                    }
                    reader.readAsDataURL(file);
                } else {
                    previewImage.style.display = 'none';
                }
    
                filePreview.style.display = 'block';
            }
    
            // 重置文件预览
            function resetPreview() {
                selectedFile = null;
                previewName.textContent = '';
                previewType.textContent = '';
                previewSize.textContent = '';
                previewImage.src = '#';
                previewImage.style.display = 'none';
                filePreview.style.display = 'none';
                fileInput.value = '';
            }
    
            // 转义 HTML 特殊字符，防止 XSS
            function escapeHtml(text) {
                const map = {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                };
                return text.replace(/[&<>"']/g, function(m) { return map[m]; });
            }
    
            // 格式化文件大小
            function formatFileSize(bytes) {
                bytes = Number(bytes);
                if (isNaN(bytes)) return '未知大小';
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
    
            // 显示提示信息
            function displayMessage(message, type) {
                const messageContainer = document.getElementById('message-container');
                const alertDiv = document.createElement('div');
                alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
                alertDiv.role = 'alert';
                alertDiv.innerHTML = `
                    ${escapeHtml(message)}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="关闭"></button>
                `;
                messageContainer.appendChild(alertDiv);
    
                // 自动移除提示信息 after 5 seconds
                setTimeout(() => {
                    alertDiv.classList.remove('show');
                    alertDiv.classList.add('hide');
                    alertDiv.remove();
                }, 5000);
            }
        });
    </script>
</body>
</html>